#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# md5fdupl.py
#
# Copyright (c) 2008, Andrey Usov <uandrey@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


__version = "0.1"

import os, sys

def scan_directory(directory):
    """
    scan directory for *.files
    - directory: directory for *.files
    return: list of *.files in specific directory
    """
    files = []
    for file in os.listdir(directory):
        if file.lower().endswith(".files"): files.append(file) 
    return files

def load_md5data_detail(filename):
    """
    load md5data from file with all information about file (md5, datetime, size, filename)
    - filename: filename of md5data
    
    return: md5data of the file
    """
    files = {}
    try:
        file = open(filename, 'r')
        while 1:
            line = file.readline()
            if line[-1:] == "\n": line = line[:-1]
            if not line: break
                
            fields = line.split("\t")
            try:
                filedata = files[fields[0]]
                filedata.append((fields[3], fields[2], fields[1]))
                files[fields[0]] = filedata
            except KeyError:
                files[fields[0]] = [(fields[3], fields[2], fields[1]),]
        file.close()
    except IOError:
        pass
    return files

def load_md5data(filename):
    """
    load md5data from file
    - filename: filename of md5data
    
    return: md5data of the file
    """
    data = []
    try:
        file = open(filename, "r")
        while 1:
            line = file.readline()
            if line[-1:] == "\n": line = line[:-1]
            if not line: break
                
            fields = line.split("\t")
            data.append(fields[0])
        file.close()
    except IOError:
        pass
    return data

def load_index_data(filename):
    """
    Load md4data index
    - filename: filename of md5data index
    
    return: index data
    """
    data = {}
    try:
        file = open(filename, "r")
        while 1:
            line = file.readline()
            if line[-1:] == "\n": line = line[:-1]
            if not line: break
                
            fields = line.split("\t")
            data[fields[0]] = fields[1]
        file.close()
    except IOError:
        pass
    return data

def save_index_data(filename, data):
    """
    save index data
    - filename: filename of md5data index
    - data: updated data of index
    """
    try:
        file = open(filename, "w")
        for k in data.keys():
            file.write("%s\t%s\n" % (k, data[k]))
        file.close()
    except IOError:
        print "Error! Cannot save data for index"
        pass
        sys.exit(1)
    

def select_index_data(index_data, filename):
    """
    select md5data for specific filename
    - index_data: index data
    - filename: filename for selection data
    
    return: slice of index_data based of filename
    """
    data = {}
    for item in index_data:
        if filename in index_data[item].split(","): data[item] = index_data[item]
    return data

def index_data_get_filenames(index_data):
    """
    get filenames from index data
    """
    filenames = []
    for item in index_data:
        files = index_data[item].split(",")
        for file in files:
            if file == "": continue
            if file in filenames: continue
            else:
                filenames.append(file)
    return filenames